package com.control.cn.core;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.control.cn.model.ServiceResult;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;

/**
 * 服务端控制
 * @Description: 
 * @author wangzonghui
 * @date 2018年10月22日 上午11:24:56
 */
@Controller
public class EurekaController {
	
	@Resource
	private EurekaClient eurekaClient;
	
	/**
	 * @description 获取服务数量和节点数量
	 * @author fuwei.deng
	 * @date 2017年7月21日 下午3:36:24
	 * @version 1.0.0
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/home", method = RequestMethod.GET)
	public ServiceResult<String> home(){
	    List<Application> apps = eurekaClient.getApplications().getRegisteredApplications();
	    int appCount = apps.size();
	    int nodeCount = 0;
	    for(Application app : apps){
	    	nodeCount += app.getInstancesAsIsFromEureka().size();
	    }
	    return new ServiceResult(0L,"appCount:"+ appCount+" nodeCountP:"+nodeCount); //(0l,"appCount",+ appCount+"nodeCount", nodeCount
	}

	/**
	 * @description 获取所有服务节点
	 * @author fuwei.deng
	 * @date 2017年7月21日 下午3:36:38
	 * @version 1.0.0
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/apps", method = RequestMethod.GET)
	public ServiceResult<String> apps(){
	    List<Application> apps = eurekaClient.getApplications().getRegisteredApplications();
	    Collections.sort(apps, new Comparator<Application>() {
	        public int compare(Application l, Application r) {
	            return l.getName().compareTo(r.getName());
	        }
	    });
	    return new ServiceResult(0L,apps);
	}
	
	/**
	 * 动态修改节点状态
	 * @param appName
	 * @param instanceId
	 * @param status
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "status/{appName}", method = RequestMethod.GET)
	public  ServiceResult<String> status(@PathVariable String appName, String instanceId, String status){
	    Application application = eurekaClient.getApplication(appName);
	    InstanceInfo instanceInfo = application.getByInstanceId(instanceId);
	    System.out.println(instanceInfo.getHomePageUrl() + "eureka-client/status  "+ "status=" + status);
//	    HttpUtil.post(instanceInfo.getHomePageUrl() + "eureka-client/status", "status=" + status); //http://172.16.37.95:2001/status/eureka-control?instanceId=localhost:2001&status=up
	    return new ServiceResult(0L,"","");
	}
}
